package com.itcoon.transform.base.pool;

import com.itcoon.transform.base.definition.ModelDefinition;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class AssembleBeanHolder {

    private static final AssembleBeanHolder BEAN_HOLDER = new AssembleBeanHolder();
    private Map<Class<?>, ConcurrentHashMap<Class<?>,ModelDefinition>> map = new ConcurrentHashMap<>();

    private AssembleBeanHolder() {
    }

    public static AssembleBeanHolder getInstance() {
        return BEAN_HOLDER;
    }

    public void addTargetClasses(Collection<Class<?>> targetClasses) {
        for (Class<?> targetClass : targetClasses) {
            map.put(targetClass, new ConcurrentHashMap<>());
        }
    }

    public Set<Class<?>> getAllTargetClass() {
        return map.keySet();
    }

    public ModelDefinition getModelDefinition(Class<?> targetClass, Object source) {
        if (targetClass == null || source == null) {
            return null;
        }
        Class<?> sourceType = source.getClass();
        if(map.get(targetClass) == null){
            addTargetClasses(Collections.singleton(targetClass));
        }
        Map<Class<?>, ModelDefinition> originMap = map.get(targetClass);
        for (Class<?> originClass : originMap.keySet()) {
            if(originClass.isAssignableFrom(sourceType)){
                return originMap.get(originClass);
            }
        }
        return null;
    }

    public void registerModelDefinition(ModelDefinition md) {
        if (md != null) {
            ConcurrentHashMap<Class<?>, ModelDefinition> originMap = map.get(md.getTargetClass());
            originMap.put(md.getOriginClass(), md);
        }
    }
}
